package com.walterweimod.auxiliary_attributes.event;

import com.google.common.collect.Lists;
import com.google.common.primitives.Floats;
import com.walterweimod.auxiliary_attributes.attribute.ModAttributes;
import com.walterweimod.auxiliary_attributes.util.ModRandomUtils;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.damagesource.EntityDamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeMap;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.ArrayList;
import java.util.Objects;

import static com.walterweimod.auxiliary_attributes.Auxiliary_attributes.*;

@Mod(MODID)
@Mod.EventBusSubscriber
public class DefenseEvent {
    @SubscribeEvent(priority = EventPriority.HIGH)
    public static void defenseAttack(LivingHurtEvent livingHurtEvent){
        DamageSource source = livingHurtEvent.getSource();
        LivingEntity defender = livingHurtEvent.getEntityLiving();

        if (source instanceof EntityDamageSource){
            Entity sourceEntity = source.getEntity();

            if (sourceEntity instanceof LivingEntity attacker){
                AttributeMap attributeMap = defender.getAttributes();
                AttributeInstance defense = attributeMap.getInstance(ModAttributes.DEFENSE.get());
                AttributeInstance special_defense = attributeMap.getInstance(ModAttributes.SPECIAL_DEFENSE.get());

                if (Objects.nonNull(defense)){
                    double defense_value = defense.getValue();
                    float base_amount = livingHurtEvent.getAmount();

                    getLogger().info("目前角色防御力为：" + defense_value);

                    ArrayList<Float> defense_value_list = Lists.newArrayList();

                    defense_value_list.add(((float) defense_value));

                    if (Objects.nonNull(special_defense)){
                        defense_value_list.add(((float) special_defense.getValue()));
                    }

                    livingHurtEvent.setAmount(ModRandomUtils.afterDefense(
                            base_amount,
                            attacker.getHealth(),
                            defender.getMaxHealth(),
                            defense_value_list
                    ));
                }
            }
        }
    }
}
